<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->load->model('Product_m', 'm');
        $this->pageSize = $this->config->item('pagenum');
		//新版下架去掉
        //$this->status = array("1" => '新品', "2" => '正常销售', "3" => '重点产品', "4" => '停产', "5" => '清仓', "6" => '暂停销售', "7" => '下架');
		$this->status =$this->fun->get_sys_goods_status();
		$this->proudctcate = array("1" => 'A类', "2" => 'B类', "3" => 'C类','4'=>'取消标签');
    }

    public function index()
    {
        $this->tpl->display("product/welcome.tpl");
    }

    public function attribute()
    {
        $this->tpl->assign("list", $this->db->get('db_goods_type')->result_array());
        $this->tpl->display("product/attribute.tpl");
    }

    public function category()
    {
        $this->tpl->assign("menudblist", $this->m->getcategorylist());
        $this->tpl->display("product/category.tpl");
    }

    public function productlist()
    {
        $this->pageSize = 20;
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
        $where = "";
        if ($this->input->get_post('parentsku')) {
            $where .= " AND p_parent_sku ='" . trim($this->input->get_post('parentsku')) . "'";
        }
        if ($this->input->get_post('parentid')) {
            $where .= " AND S.goods_parentID='" . trim($this->input->get_post('parentid')) . "'";
        }
        //发货仓库
        $shippingStatus = $this->input->get_post('shippingStatus');
        if($shippingStatus){
            $sql = "SELECT GROUP_CONCAT(goods_id) as goods_id FROM db_goods_stock WHERE storage_id ='{$shippingStatus}' ";
            $rs  = $this->db->query($sql)->row_array();
          
            if($rs['goods_id']){
                $rs['goods_id'] = trim($rs['goods_id'],",");
                $where .= " AND S.goods_id in ({$rs['goods_id']})";
            }else{
                $where .= " AND S.goods_id = '' ";
            }
            $this->tpl->assign("shippingStatus",$shippingStatus);
        }
        if ($this->input->get_post('goods_id')) {
            $where .= " AND S.goods_id='" . trim($this->input->get_post('goods_id')) . "'";
        }
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.="  AND S.g_supplier= 1";
		}
		if($_COOKIE["classid"] ==16)	//外包工厂
		{
			$where.="  AND S.g_supplier= 7";
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND S.g_supplier = 2";
		}

	    if ($this->input->get_post('supplier') && $_COOKIE["classid"]!=12 && $_COOKIE["classid"] !=13 && $_COOKIE["classid"] !=16) {
            $where .= " AND S.g_supplier='" . trim($this->input->get_post('supplier')) . "'";
			$this->tpl->assign("supplier", trim($this->input->get_post('supplier')));
        }
		
		$filtertype = trim($this->input->get_post('filtertype'));
		
		if($filtertype)
		{
			$filtersql = $filtertype;
			if($filtertype=='noprice'){
				$where .= " and  (S.g_costprice = 0) ";
			}
			if($filtertype=='nobulkprice'){
				$where .= " and  length(S.goods_parent_sku)=8 AND (locate(11,S.goods_parent_sku)=1 or locate(12,S.goods_parent_sku)=1 ) and length(S.goods_sku)<8 AND S.bulkprice =0 ";
			}
			if($filtertype=='isbulk'){
				$where .= " and  length(S.goods_parent_sku)=8 AND (locate(11,S.goods_parent_sku)=1 or locate(12,S.goods_parent_sku)=1 ) and length(S.goods_sku)<8 ";
			}
			if($filtertype=='ispositions'){
				$where.= " AND goods_id in(SELECT goods_id FROM `db_goods_stock` WHERE positions like '%".trim($this->input->get_post('other'))."%')";
			}
			$this->tpl->assign("filtertype", $filtertype);
		}
		
        if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
			

            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r){
                    if ($key > 0) $k = "or";

					if($filtertype=='skuc')
					{
						$where .= " $k S.goods_sku LIKE  '" . $r . "' ";
					}elseif($filtertype=='nobulkprice'){
						$where .= " $k S.goods_sku LIKE  '%" . $r . "%' ";
					}elseif($filtertype=='noprice'){
						
					}elseif($filtertype=='isbulk'){
						
					}elseif($filtertype=='ispositions'){
					}elseif($filtertype=='warehouse'){
                    }elseif($filtertype=='cognatelist'){
						$where .= " $k S.cognatelist LIKE  '%," . $r . ",%' ";
                    }else{
						if(!$filtertype)
						{
							$where .= " $k S.goods_sku LIKE  '%" . $r . "%' ";
						}else{
							$where .= " $k S.$filtersql LIKE  '%" . $r . "%' ";
						}
					}
                    
                }
                $where .= ")";

            } else {
					if($filtertype=='skuc')
					{
						$where .= " and  (S.goods_sku LIKE  '" . $other . "') ";
					}elseif($filtertype=='nobulkprice'){
						
					}elseif($filtertype=='noprice'){
						
					}elseif($filtertype=='isbulk'){
						
					}elseif($filtertype=='ispositions'){
					}elseif($filtertype=='warehouse'){
                    }elseif($filtertype=='cognatelist'){
						$where .= " and (S.cognatelist LIKE  '%," . $other . ",%') ";
                    }else{
						

						if(!$filtertype)
						{
							$where .= " and  (S.goods_sku LIKE  '%" . $other . "%' or S.goods_name LIKE  '%" . $other . "%') ";
						}else{
							$where .= " and  (S.$filtersql LIKE  '%" . $other . "%') ";
						}
					}

                
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }
        
        if ($this->input->get_post('status')) {
            $where .= " AND g_sale_status='" . trim($this->input->get_post('status')) . "'";
            $this->tpl->assign("status", trim($this->input->get_post('status')));
        }
        if ($this->input->get_post('bigclassID')) {
            $where .= " AND g_bigclassid='" . trim($this->input->get_post('bigclassID')) . "'";
            $this->tpl->assign("bigclassID", trim($this->input->get_post('bigclassID')));
        }
        if ($this->input->get_post('secondclassID')) {
            $where .= " AND g_secondclassid='" . trim($this->input->get_post('secondclassID')) . "'";
            $this->tpl->assign("secondclassID", trim($this->input->get_post('secondclassID')));
        }
        
        if ($this->input->get_post('ty')) {
            $ty = $this->input->get_post('ty');
            switch ($ty) {
                case 1:
                    $starttime = trim($this->input->get('starttime'));
                    if ($starttime) {
                        $times = $starttime . " 00:00:00";
                        $where .= " AND (S.g_updatetime >= '" . $times . "')";
                        $this->tpl->assign("starttime", $starttime);
                    }

                    $endtime = trim($this->input->get('endtime'));
                    if ($endtime) {
                        $times = $endtime . " 23:59:59";
                        $where .= " AND (S.g_updatetime <= '" . $times . "')";
                        $this->tpl->assign("endtime", $endtime);
                    }
                    break;
                case 2:
                    $salestarttime = trim($this->input->get('starttime'));

                    $saleendtime = trim($this->input->get('endtime'));
					 $this->tpl->assign("starttime", $salestarttime);
					  $this->tpl->assign("endtime", $saleendtime);
                    break;
            }

            $this->tpl->assign("ty", trim($this->input->get_post('ty')));
        }
		 if ($this->input->get_post('other')) {
			  $orderby = " order by goods_id DESC,dailysales DESC";
		 }else{
			  $orderby = " order by goods_id DESC";
		 }
		if($this->input->get('iscsv')==1)$if_csv=1;
        $list = $this->m->getproductlist('db_goods_parent', $where, $nowpage, $if_csv, $this->pageSize, $orderby);
      
		
        $goodslist = $list["list"];
		$goods_sku_list=$parent_sku=array();
        foreach ($goodslist as $key => $rs) {
			$parent_sku_list[]=strtoupper($rs['p_parent_sku']);
			$saleN = $this->m->getallstock($rs["p_parent_id"]);
			$goodslist[$key]["allstock"] = $saleN['allstock'];	//总库存数
			$goodslist[$key]["allsale"] = $saleN['salenum'];	//总库存数
            $bigclass = $this->m->goodscategory($rs["p_bigclassid"]);
            $goodslist[$key]["p_bigclassname"] = $bigclass["cate_name"];
            $secondclass = $this->m->goodscategory($rs["p_secondclassid"]);
            $goodslist[$key]["p_secondclassname"] = $secondclass["cate_name"];
            $threeclass = $this->m->goodscategory($rs["p_threeclassid"]);
            $goodslist[$key]["p_threeclassname"] = $threeclass["cate_name"];
            $goodslist[$key]["salestatus"] = $this->status[$rs["p_sale_status"]];
            //$this->db->select('goods_sku, goods_name, g_costprice');db_goods_stock A
			$this->db->order_by("goods_sku", 'ASC');
			if($this->config->item('isopenclosedgoods') ==0){	//管理员可见
				if( $_COOKIE['department']==1)
				{
					$ysa = "(yz = 0 or yz = 2)";
				}else{
					$ysa = "yz = 0";
				}
			}elseif($this->config->item('isopenclosedgoods') ==1){	// 管理员和主管可见
				if( $_COOKIE['department']==1 ||  $_COOKIE['department'] == 2)
				{
					//管理员和主管可以看到停售的商品
					$ysa = "(yz = 0 or yz = 2)";
				}else{
					$ysa = "yz = 0";
				}
			}elseif($this->config->item('isopenclosedgoods') ==2){	//所有人可见
				 $ysa = "(yz = 0 or yz = 2)";
			}elseif($this->config->item('isopenclosedgoods') ==3){	//所有人不可见
				 $ysa = "yz = 0";
			}

            
			if(($this->config->item('isopensearchjinque')==1 || $_COOKIE['classid']==10 || $filtertype=='skuc'))
			{
				 $songoodslist = $this->db->get_where('db_goods  S', " 1 $where AND {$ysa} AND goods_parentID=" . $rs["p_parent_id"])->result_array();
			}else{
				 $songoodslist = $this->db->get_where('db_goods ', " {$ysa} AND goods_parentID=" . $rs["p_parent_id"])->result_array();
			}
			
            $allsendgoodsnum=0;
			$stockPrice = 0;//总库存价值
            foreach ($songoodslist as $k => $r) {
                //图片
				$goods_sku_list[]=strtoupper($r['goods_sku']);
				//获取销量
				if(intval($this->input->get('saledays')))
				{
				
					$saledays = intval(trim($this->input->get('saledays')));
					$newtime = $saledays*86400;
					$st = date("Y-m-d",time()-$newtime);
					$songoodslist[$k]["allday1"] = $this->fun->get_goods_sale($r["goods_id"],$st,date("Y-m-d"));
					$songoodslist[$k]["allfbaday1"] = $this->fun->get_goods_fba_sale($r["goods_id"],$st,date("Y-m-d"));
					$songoodslist[$k]["totalday1"] = $songoodslist[$k]["allday1"]+$songoodslist[$k]["allfbaday1"];

				}
				//通过时间获取销售
				if(trim($salestarttime))
				{

					$songoodslist[$k]["allday1"] = $this->fun->get_goods_sale($r["goods_id"],$salestarttime,$saleendtime);
					$songoodslist[$k]["allfbaday1"] = $this->fun->get_goods_fba_sale($r["goods_id"],$salestarttime,$saleendtime);
					$songoodslist[$k]["totalday1"] = $songoodslist[$k]["allday1"]+$songoodslist[$k]["allfbaday1"];
					
				}
				
				$songoodslist[$k]["allsales1"] = $r['sales1']+$r['fbasale1'];
				$songoodslist[$k]["allsales2"] = $r['sales2']+$r['fbasale2'];
				$songoodslist[$k]["allsales3"] = $r['sales3']+$r['fbasale3'];


                $goods_images = "";
                $thumb_url = "";
                $goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $r["goods_id"])->result_array();
                $thumb_url = $goods_images[0]["thumb_url"];
			
                if ($thumb_url) {
                    $songoodslist[$k]["imagesurl"] = $thumb_url;
                }elseif ($goods_images[0]['local_url']) {
                    $songoodslist[$k]["imagesurl"] = "/".$goods_images[0]['local_url'];
                }elseif ($goods_images[0]['images_url']) {
                    $songoodslist[$k]["imagesurl"] = "/".$goods_images[0]['imagesurl'];
                } else {
					//如果没有获取到图片，再次读取父商品的图片
                    $songoodslist[$k]["imagesurl"] = "/fuman/images/s-l500.jpg";
                }
                /***库存信息**/
                $storage = $this->db->get_where('db_goods_stock', " goods_id = '" . $r["goods_id"] . "'")->result_array();
				foreach($storage as $keycag=>$cangs)
				{
					//获取待发货数量
					$sendgoodsnum = $this->m->getsendthegoods($r['goods_id'],$cangs['storage_id']);
					$allsendgoodsnum = $allsendgoodsnum+$sendgoodsnum;
					$storage[$keycag]["sendgoodsnum"] = $sendgoodsnum;
					$storage[$keycag]["waitday"] = date("Y-m-d",$cangs['waitday']);

                    //库存
                    $stock = $this->db->get_where('db_storage', " id = '" . $cangs["storage_id"] . "'")->row_array();
                    $storage[$keycag]["is_show"] = $stock['is_show'];

					//获取成本
					if($this->fun->getfactorygoodsku($r["goods_sku"]) == false)
					{
						$SKUcostprice  = $this->fun->get_Goods_costprice($r["goods_sku"]);
						if($cangs["stock"]>0)
						{
							$stockPrice = $stockPrice+($cangs["stock"] * $SKUcostprice);
						}
						}
				
				}
                $songoodslist[$k]["storage"] = $storage;
                $songoodslist[$k]["goods_sku"]=strtoupper($r['goods_sku']);
                
                //属性
                $goods_attrlist = $this->db->get_where('db_goods_attr', 'goods_id=' . $r["goods_id"])->result_array();
                $songoodslist[$k]["goods_attrlist"] = $goods_attrlist;
                $songoodslist[$k]["status"] = $this->status[$r["g_sale_status"]];
            }
			
			$goodslist[$key]["allsendgoodsnum"] = $allsendgoodsnum;	//总待发货数
			$goodslist[$key]["stockPrice"] = $stockPrice;
            $goodslist[$key]["songlist"] = $songoodslist;

        }
        //dump($goodslist);
        $oversea_arr=$overseadata=array();
        if(count($goods_sku_list)>0){
		    $sku_strs=implode("','",$goods_sku_list);
            $overseadata=$this->db->select('id,hw,st,sku')->get_where('t_overseaproduct', "sku in('".$sku_strs."')")->result_array();  
        }
        foreach($overseadata as $key=>$overseainfo){
            $oversea_arr[$overseainfo['sku']]=$overseainfo;
        }

		//是否侵权
		$infringement_arr=$infringementdata=array();
        if(count($parent_sku_list)>0){
		    $sku_strs=implode("','",$parent_sku_list);
			$infringementdata=$this->db->select('id,reason,p_parent_sku,addTime,createUser')->get_where('db_goods_status', "p_parent_sku in('".$sku_strs."') and type=3")->result_array();  
        }
		if(count($infringementdata)>0){
        foreach($infringementdata as $key=>$infringementdata_detail){
            $infringement_arr[$infringementdata_detail['p_parent_sku']]=$infringementdata_detail;
        }
		}
		
		if($this->input->get('saledays') || $salestarttime)
		{
			$this->tpl->assign("saledays", trim($this->input->get('saledays')));
			if($salestarttime){
			$this->tpl->assign("salestarttime", date("m/d",strtotime($salestarttime)));
			$this->tpl->assign("saleendtime", date("m/d",strtotime($saleendtime)));
			}

		}else{
			$saleskumonth  = trim($this->config->item('saleskumonth'));
			if($saleskumonth)
			{
				$days = explode("|",$saleskumonth);
				$i = 0;
				foreach($days as $key => $rs)
				{
					if($key ==0) $this->tpl->assign("day1", $rs);
					if($key ==1) $this->tpl->assign("day2", $rs);
					if($key ==2) $this->tpl->assign("day3", $rs);
				}
				
			}else{
				$this->tpl->assign("day1", 30);
				$this->tpl->assign("day2", 60);
				$this->tpl->assign("day3", 90);
			}
		}
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign('oversea_arr',$oversea_arr);
		 $this->tpl->assign('infringement_arr',$infringement_arr);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("salestatus", $this->status);
		$this->tpl->assign("proudctcate", $this->proudctcate);
        $this->tpl->assign("productlistissong", $this->config->item('productlistissong'));//默认不子商品
        $this->tpl->assign("productlistisparent", $this->config->item('productlistisparent'));    //是否显示父类
        $this->tpl->assign("warehouses",$this->db->get_where("db_storage",array('isdel'=>0))->result_array());
        $this->tpl->assign("goodslist", $goodslist);
		$this->tpl->assign("factory", $this->m->getfactory());
		$this->tpl->assign('userlist',$this->fun->userlist('2,3,8,9,19,14'));
			
		if($this->input->get('iscsv')==1)
		{
			/*
			$headers =array("商品编号","关联编号","成本价","关联价","工价");
			  foreach($goodslist as $key=>$rs){
				  foreach($rs["songlist"] as $s=>$v){
					$listdata[$key][$s][] = $v["goods_parent_sku"]; 
					$listdata[$key][$s][] = $v["goods_sku"]; 
					$listdata[$key][$s][] = $v["g_costprice"]; 
					$listdata[$key][$s][] = $v["bulkprice"]; 
					$listdata[$key][$s][] = $v["wages"]; 
				}
			}
		
			$this->fun->ouputexclePro($headers,$listdata);
			die;*/
			 //导出excel表格
			  header("Content-type:application/vnd.ms-excel");
			  header("Conten-type:text/html;charset=utf-8");
			  header("Content-Disposition:filename=product.xls");
					
            echo "<table><tr>";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品编号")."</td>" ."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "关联编号")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "成本价")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "关联价")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "工价")."</td>"."\t\n";
            echo "</tr>";
          foreach($goodslist as $key=>$rs){
				  foreach($rs["songlist"] as $s=>$v){
                echo "<tr>";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['goods_parent_sku'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['goods_sku'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['g_costprice'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['bulkprice'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['wages'])."</td>"."\t\n";
                echo "</tr>";
            }
		  }
		  echo "</table>";
			die;
		}
        $categorylist = $this->db->get_where('db_goods_category', 'sort_id=0')->result_array();
        $this->tpl->assign("categorylist", $categorylist);//分类
		$this->tpl->assign("classid", $_COOKIE['classid']);
        $this->tpl->display("product/productlist.tpl");
    }

    public function setOverseaFlag(){
        $postdata=$this->input->post();
        $action=$postdata['action'];
        $sku=strtoupper($postdata['sku']);
        $flagval=$postdata['flagval'];
        $image=$flagval==1?'yes':'no';
        $insertid=0;
        switch($action){
            case "fba":
                 $image='yes';
                 $res = $this->fun->getdatabasesdetail("t_overseaproduct"," AND sku= '".$sku."'");
                 if($res==null){
                    $insertid=$this->m->createOverSeaData($sku,0);   
                 }  
                 $res = array("result" => 200,'sku'=>$sku,'insertid'=>$insertid,"img" => $image,'msg'=>'success');
            break;
            case "st":
                $sql = "UPDATE t_overseaproduct SET st =$flagval where sku = '".$sku."'";
    		    $this->db->query($sql);
                $res = array("result" => 200,'sku'=>$sku,"img" => $image,'msg'=>'success');
            break;
            case "hw":
                $res = $this->fun->getdatabasesdetail("t_overseaproduct"," AND sku= '".$sku."'");
                 if($res==null){
                    $insertid=$this->m->createOverSeaData($sku,1);   
                 }else{
                    $sql = "UPDATE t_overseaproduct SET hw = $flagval where sku = '".$sku."'";
    		        $this->db->query($sql);   
                 }
                $res = array("result" => 200,'sku'=>$sku,'insertid'=>$insertid,"img" => $image,'msg'=>'success');
            break;
        }
        echo json_encode($res);    
    }
  
    
    
    public function newproduct()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
        $where = "";
		
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND supplier = 1";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND supplier = 2";	
		}
		if($_COOKIE["classid"] ==16)	//工厂3人员
		{
			$where.=" AND supplier = 7";	
		}

        if ($this->input->get('id')) {
            $where .= " AND id = '" . $this->input->get('id') . "'";
        }
		if ($this->input->get('status')) {
            $where .= " AND status = '" . $this->input->get('status') . "'";
			$this->tpl->assign("status", trim($this->input->get_post('status')));
        }
		//操作人员
        $createName = trim($this->input->get('createName'));
        if($createName){
            $where.= " AND createName like '%".$createName."%'";
            $this->tpl->assign('createName',$createName);
        }
        $factory_id = $this->input->get('factory_id');
        if($factory_id){
            $where.= " AND supplier = $factory_id ";
            $this->tpl->assign('factory_id',$factory_id);
        }
        
        
		$ty = $this->input->get('ty');
		
		if($ty==1)$feil = "instime";
		if($ty==2)$feil = "FROM_UNIXTIME(overtime) ";
		 $this->tpl->assign("ty", $ty);
		 $starttime = trim($this->input->get('starttime'));
        if ($starttime) {
            $times = $starttime . " 00:00:00";
            $where .= " AND ({$feil} >= '" . $times . "')";
            $this->tpl->assign("starttime", $starttime);
        }

        $endtime = trim($this->input->get('endtime'));
        if ($endtime) {
            $times = $endtime . " 23:59:59";
            $where .= " AND ({$feil} <= '" . $times . "')";
            $this->tpl->assign("endtime", $endtime);
        }
		 if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k `sku` LIKE  '%" . $r . "%' or name LIKE '%" . $r . "%'";
                }
                $where .= ")";

            } else {
                $where .= " and  (sku LIKE  '%" . $other . "%'
					or name LIKE '%" . $other . "%'
					or `en_name` LIKE  '%" . $other . "%'
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }
	    //显示确认上架，取消上架相关原因
	    $users = $this->db->get_where('d_user'," type=1 ")->result_array();
	    $arr_receiver = array();
	    foreach($users as $kk=>$vv){
		    $arr_receiver[$vv['id']] = $vv['name'];
	    }
	    $this->tpl->assign("arr_receiver", $arr_receiver);


        $orderby = " order by id DESC";
        $list = $this->fun->getalllist('db_product_develop', $where, $nowpage, $if_csv, $this->pageSize, $orderby);
       // echo $this->db->last_query();
        foreach ($list["list"] as $key => $rs) {
            $list["list"][$key]["instime"] = date("Y-m-d", strtotime($rs["instime"]));
			if($rs["linkUrl_addtime"]){
				$list["list"][$key]["linkUrl_addtime"] = date("Y-m-d", strtotime($rs["linkUrl_addtime"]));
			}
			if($rs["trialtime"]>0)$list["list"][$key]["trialtime"] = date("Y-m-d", $rs["trialtime"]);
			if($rs["sampletime"]>0)$list["list"][$key]["sampletime"] = date("Y-m-d", $rs["sampletime"]);
			if($rs["reviewagain"]>0)$list["list"][$key]["reviewagain"] = date("Y-m-d", $rs["reviewagain"]);
			if($rs["overtime"]>0)$list["list"][$key]["overtime"] = date("Y-m-d", $rs["overtime"]);
			
			if($rs["supplier"] == 1)$taskerman = $this->config->item('factory1audit');	//工厂1初审人
			if($rs["supplier"] == 2)$taskerman = $this->config->item('factory2audit');	//工厂2初审人
			if($rs["supplier"] == 3)$taskerman = $this->config->item('outsidepurchasing');//外采购初审人
			if($rs["supplier"] == 7)$taskerman = $this->config->item('outsidepurchasing');//外采购初审人
            switch ($rs["status"]) {
                case 1;
                    $list["list"][$key]["statusst"] = '新开发';
					//初审
					if($taskerman){
						$packingman = explode("|",$taskerman);
						if(in_array($_COOKIE["username"],$packingman))
						{
							$list["list"][$key]["trialmod"] = 1;
						}else{
							$list["list"][$key]["trialmod"] = 0;
						}
					}
					
                    break;
                case 2;
                    $list["list"][$key]["statusst"] = '已初审';
					if($this->config->item('productsample')){	//出样填写人员权限
						if(in_array($_COOKIE["username"], explode("|",$this->config->item('productsample'))))
						{
							$list["list"][$key]["thesample"] = 1;
						}else{
							$list["list"][$key]["thesample"] = 0;
						}
					}
                    break;
                case 3;
                    $list["list"][$key]["statusst"] = '已出样';
					if($this->config->item('reviewagain')){	//复审人员权限
						if(in_array($_COOKIE["username"], explode("|",$this->config->item('reviewagain'))))
						{
							$list["list"][$key]["reviewagainmod"] = 1;
						}else{
							$list["list"][$key]["reviewagainmod"] = 0;
						}
					}
                    break;
                case 4;
                    $list["list"][$key]["statusst"] = '已复审';
					if($this->config->item('artistimages')){	//复审人员权限
						if(in_array($_COOKIE["username"], explode("|",$this->config->item('artistimages'))))
						{
							$list["list"][$key]["artistimagesmod"] = 1;
						}else{
							$list["list"][$key]["artistimagesmod"] = 0;
						}
					}
                    break;
                case 5;
                    $list["list"][$key]["statusst"] = '已出图';
                    break;
                case 6;
                    $list["list"][$key]["statusst"] = '已完成';
                    break;
				case 7;
                    $list["list"][$key]["statusst"] = '已否决';
                    break;
            }

			if($rs["status"] ==6)
			{
				$ressku = $this->fun->getdatabasesdetail("db_goods"," AND goods_parent_sku = '{$rs['sku']}' ","GROUP_CONCAT(goods_id) as  id");
				$str_goods_id = $ressku["id"];
				if($str_goods_id){
					$sql = "SELECT sum(goods_number) as saleNum FROM db_order_sell A left join db_order_list B on A.`order_id` = B.order_id  where A.`goods_id` in($str_goods_id) AND B.order_status in (4,5) ";
					$rsdb  = $this->db->query($sql)->row_array();
					if($rsdb['saleNum']>=1){
						$list["list"][$key]["showreport"] = 1;
					}else{
						$list["list"][$key]["showreport"] = 0;
					}
				}else{
					$list["list"][$key]["showreport"] = 0;
				}
			}

	        $receivers = trim($rs['receivers'],",");
	        $receivers = explode(",",$receivers);
	        //$list["list"][$key]["receivers"] = explode(",",$receivers); //所有有返回消息的接受者
	        //返回相关信息
	        $return_reason = explode(",",$rs['return_reason']);
	        $arr_msg = array();
	        foreach($receivers as $k=>$v){
		        $arr_msg[$k]['userid'] = $v;
		        $arr_msg[$k]['flag']=0;
		        $arr_msg[$k]['address']=0;
		        foreach($return_reason as $kk=>$vv){
			        $arr_reason = explode("-",$vv);

			        if($v==$arr_reason[0]){
				        $arr_msg[$k]['flag']=$arr_reason[1];
				        $str_con = $arr_reason[0]."-".$arr_reason[1]."-";
				        $arr_msg[$k]['address']=str_replace($str_con,"",$vv);
				        break;
			        }
		        }
	        }
	        $list["list"][$key]["receivers"] = $arr_msg; //所有有返回消息的接受者


            if ($_COOKIE["username"] == $rs["createName"]) {
                $list["list"][$key]["mod"] = 1;
            } else {
                $list["list"][$key]["mod"] = 0;
            }
			$ProductImages = $this->m->getProductImages($rs["id"]);
			if($ProductImages)
			{
				$imgurl = dirname(__FILE__) . "/../..".$ProductImages[0]["thumb_url"];
				if(file_exists($imgurl))
				{
					 $list["list"][$key]["images"] = $ProductImages[0]["thumb_url"];
				}else{
					$list["list"][$key]["images"] = "/fuman/images/s-l500.jpg";
				}
			}else{
				$list["list"][$key]["images"] = "/fuman/images/s-l500.jpg";
			}
			
        }
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("goodslist", $list["list"]);
		$this->tpl->assign("versiondivision", $this->fun->userlist(12));	//打版师
		if($this->config->item('sysbodystandard')){
		$bodystandard = array_unique(explode("|",trim($this->config->item('sysbodystandard'))));
		$this->tpl->assign("bodystandard",$bodystandard);
		}

	    //推荐新品开发接收者
	    $receivers_config = trim($this->config->item('externalbuyreceivers'));
	    $arr_receiver_config = explode("|",$receivers_config);
	    $str_receiver = "";
	    foreach($arr_receiver_config as $k=>$v){
		    $str_receiver.= "'".trim($v)."'".",";
	    }
	    $str_receiver = trim($str_receiver,",");
	    $receiverlist = $this->db->get_where('d_user'," type=1  AND name in ($str_receiver) ")->result_array();
	    $this->tpl->assign("receiverlist", $receiverlist);


		//获取所有物料分类
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$sqlwhere=" AND factoryid = 12";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$sqlwhere=" AND factoryid = 13";	
		}
		$material = $this->fun->getdatabaseslist("db_factory_material",$sqlwhere," DISTINCT(typename) as typename");
		$this->tpl->assign("materiallist",$material);
		 $this->tpl->assign("receiverlistinstructions",$this->config->item('externalbuyreceivers_instructions') );
        $this->tpl->display("product/newproduct.tpl");
    }

    public function addNewprodct()
    {
        $detail = $this->db->get_where('db_product_develop', " id='" . $this->input->get('id') . "'")->result_array();
		$detailmaterial = $this->db->get_where('db_product_develop_material', " develop_id='" . $this->input->get('id') . "'")->result_array();
        $this->tpl->assign("factory", $this->m->getfactory());
        $this->tpl->assign("detail", $detail[0]);
		$this->tpl->assign("detailmaterial", $detailmaterial);
		

		
		if($_COOKIE["classid"] ==16)	//外包工厂
		{
			$this->tpl->assign("swdetail", 1);
		}
		

		if($this->input->get('show')==1)
		{
			$this->tpl->display("product/addNewprodctshow.tpl");
		}else{
            $sku = trim($this->input->get('sku'));//外采购sku
            $sql = "SELECT * FROM db_external_buy WHERE sku = '{$sku}' AND del_flag = 0 ";
            $rs  = $this->db->query($sql)->row_array();
            $this->tpl->assign("arr_externalbuy",$rs);
            $this->tpl->assign("sku",$sku);

			$this->tpl->display("product/addNewprodct.tpl");
		}
	}

    public function editProduct()
    {
        $categorylist = $this->db->get_where('db_goods_category', 'sort_id=0')->result_array();
        $this->tpl->assign("categorylist", $categorylist);//分类
        $goods_id = $this->input->get('goods_id', true);
		$sku = $this->input->get('sku');
			
		if($_COOKIE['ext_userid'])
		{
			if($_COOKIE['ext_userid_open_goods'] == 1)	//允许查看自己组和非其他组的商品
			{
				
				$externalList = $this->fun->getdatabasesdetail('d_user_external'," AND id !='".$_COOKIE['external_id']."'",'GROUP_CONCAT(external_userID) as Createid');
				$ext_userID = $externalList['Createid'];
				$where.=" AND (g_createID not in ($ext_userID))";
			}else{
				//只能查看自己组
				$ext_userID = $_COOKIE['ext_userid'];
				$where=" AND (g_createID in ($ext_userID) or g_checkman like '".$_COOKIE["username"]."')";
			}
		}
		

	



		if($sku)
		{
			 $goods = $this->fun->getdatabasesdetail('db_goods', " $where AND goods_sku = '" . $sku . "'");    //商品信息
			 $goods_id = $goods["goods_id"];
		}else{
			 $goods = $this->fun->getdatabasesdetail('db_goods', " $where AND goods_id = '" . $goods_id . "'");    //商品信息
		}
		if(!$goods)
		{
			die("Error");
		}
        
       
        $goods_attrlist = $this->db->get_where('db_goods_attr', 'goods_id=' . $goods_id)->result_array();//商品属性
        $goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $goods_id)->result_array();    //商品图片
        $this->db->order_by("id", 'DESC');
        $this->db->limit($this->config->item('configlognum'));
        $goods_log = $this->db->get_where('db_goods_log', 'types = 1 AND goods_id=' . $goods_id)->result_array();    //商品日志
		
		if($goods["goods_parent_sku"])
		{
			$rsdb  = $this->db->get_where("db_factory"," code >0")->result_array();
			foreach($rsdb as $key =>$rs)
			{
				$factorycode[] = $rs["code"];	//工厂编号
			}
			if(is_numeric($goods["goods_parent_sku"]) && preg_match('|^\d{8}$|',$goods["goods_parent_sku"]))	//数字并且8位//判断是否是符合导订的要求 //8位SKU并且11 12开头
			{
				$goodscode  = substr($goods["goods_parent_sku"],0,2);
				if(in_array($goodscode,$factorycode))
				{
					if(!$goods['g_goodstypeID'] && $goods["goods_sku"] !=$goods["goods_parent_sku"])
					{
						$goods['g_goodstypeID'] = 7;
					}
				}
			}
		}
		
        //属性值
        if ($goods['g_goodstypeID']) {
            $attributelist = $this->db->get_where('db_attribute', 'cat_id=' . $goods['g_goodstypeID'])->result_array();
            foreach ($attributelist as $key => $rs) {
                $rbute = $this->fun->getdatabasesdetail('db_goods_attr', " AND goods_id='" . $goods_id . "' AND attr_id='" . $rs["attr_id"] . "'");
                if ($rbute["attr_value"]) {
                    $attributelist[$key]["selectvalue"] = $rbute["attr_value"];

                }
                $attributelist[$key]["selectvaluelist"] = explode("\r\n", $rs["attr_values"]);
            }
            $this->tpl->assign("attributelist", $attributelist);
        }
		
		//历史订单信息
		$orderhistoryList = $this->m->getorderhistoryList($goods_id);
		if($orderhistoryList)
		{
			 $this->tpl->assign("orderhistoryList", $orderhistoryList);
		}else{
			$getorderhistoryFBAList = $this->m->getorderhistoryFBAList($goods_id);
			$this->tpl->assign("getorderhistoryFBAList", $getorderhistoryFBAList);
			
		}

		//历史FBA订单信息
		/*
		$orderhistoryFBAList = $this->m->getorderhistoryFBAList($goods_id);
		if($orderhistoryFBAList)
		{
			 $this->tpl->assign("orderhistoryFBAList", $orderhistoryFBAList);
		}*/
		
		if($goods['g_supplier']==3)
		{
			$businessman = $this->db->get_where('db_goods_purchasing', " goods_id = '" . $goods_id . "'")->result_array();
			$this->tpl->assign("businessman", $businessman);
		}else{
			$this->tpl->assign("businessman", "");
		}

		
        /***库存信息**/
        $storage = $this->db->get_where('db_goods_stock', " goods_id = '" . $goods_id . "'")->result_array();
        $this->tpl->assign("storage", $storage);
        $this->tpl->assign("salestatus", $this->status);
        $userlist = $this->db->get_where('d_user', 'classid in (2,3,4,5,6,8,14) and type=1')->result_array();
        $this->tpl->assign("userlist", $userlist);
        $this->tpl->assign("goods", $goods);
        $this->tpl->assign("goods_attrlist", $goods_attrlist);
        $this->tpl->assign("goods_images", $goods_images);
        $this->tpl->assign("goods_log", $goods_log);
        $this->tpl->assign("factory", $this->m->getfactory());
		$this->tpl->assign("classid", $_COOKIE['classid']);
        $this->tpl->display("product/editProduct.tpl");
    }

    public function storage()
    {
        $storagelist = $this->db->get_where('db_storage', 'isdel=0')->result_array();
        $this->tpl->assign("storagelist", $storagelist);
        $this->tpl->display("product/storage.tpl");
    }

    public function addprodct()
    {
		$sku = trim($this->input->get('sku'));
		if($sku){
			$detail["goods_sku"] = $sku;
			$this->tpl->assign("goods", $detail);
		}

        $categorylist = $this->db->get_where('db_goods_category', 'sort_id=0')->result_array();
        $this->tpl->assign("categorylist", $categorylist);
        $attribute = $this->db->get('db_goods_type')->result_array();
        $userlist = $this->db->get_where('d_user', 'classid in (2,3,4,5,6,8,14) and type=1')->result_array();
        $this->tpl->assign("userlist", $userlist);
        $this->tpl->assign("salestatus", $this->status);
        $this->tpl->assign("attribute", $attribute);
		
        $this->tpl->assign("factory", $this->m->getfactory());
        $this->tpl->display("product/addproduct.tpl");
    }

    public function addParentProduct()
    {
        $pid = $this->input->get('pid');
        $goods = $this->fun->getdatabasesdetail('db_goods_parent', " AND p_parent_id = '" . $pid . "'");    //父商品信息
		$addgoodsno = $this->input->get('goodsno');//获取从待审核订单中添加的商品SKU
		$this->tpl->assign("addgoodsno", $addgoodsno);
		$goods["status"] = $this->status[$goods["p_sale_status"]];

		//采购信息
		if($goods['businessman']){
			$businessman = unserialize($goods['businessman']);
			$businessmanline = unserialize($goods['businessmanline']);
			$this->tpl->assign("businessman", $businessman);
			$this->tpl->assign("businessmanline", $businessmanline);
		}
		//判断是否为工厂定制的SKU商品
		if($this->fun->getfactorygoodsku($goods['p_parent_sku']))
		{
			$this->tpl->assign("factorygoodsku", 1);
		}

		//每次打开自动生成一个5位的关联ID
		$autolikesku = $this->fun->getlinktosku($goods["p_parent_sku"]);
		//自动生成亚洲的五位关联ID
		$yaautolikesku = $this->fun->getlinktosku($goods["p_parent_sku"],0,1);
		if($yaautolikesku ==$autolikesku)	//如果两个SKU相同，则亚洲的自动生成一个
		{
			$yaautolikesku = $this->fun->getlinktosku($goods["p_parent_sku"],1,1);
		}
		$this->tpl->assign("autolikesku", $autolikesku);
		$this->tpl->assign("yaautolikesku", $yaautolikesku);
		/***当前有多少子SKU*******/
		$goodsson = $this->fun->getdatabasesdetail('db_goods', " AND goods_parentID = '" . $pid . "'","count(goods_id) as goodsnum");
		 $this->tpl->assign("goodsnum", $goodsson['goodsnum']);
        $categorylist = $this->db->get_where('db_goods_category', 'sort_id=0')->result_array();
        $attribute = $this->db->get('db_goods_type')->result_array();
        $userlist = $this->db->get_where('d_user', 'classid in (2,3,4,5,6,8,14)')->result_array();
        $this->tpl->assign("userlist", $userlist);
        $this->tpl->assign("attribute", $attribute);
        $this->tpl->assign("salestatus", $this->status);
        $this->tpl->assign("categorylist", $categorylist);//分类
        $this->tpl->assign("goods", $goods);//父商品信息
        $this->tpl->assign("factory", $this->m->getfactory());
        $this->tpl->display("product/addParentProduct.tpl");
    }

	public function EditParentProduct()
	{
		 $pid = $this->input->get('pid');
        $goods = $this->fun->getdatabasesdetail('db_goods_parent', " AND p_parent_id = '" . $pid . "'");    //父商品信息
		$addgoodsno = $this->input->get('goodsno');//获取从待审核订单中添加的商品SKU
		$this->tpl->assign("addgoodsno", $addgoodsno);
		$goods["status"] = $this->status[$goods["p_sale_status"]];

		
		//判断是否为工厂定制的SKU商品
		if($this->fun->getfactorygoodsku($goods['p_parent_sku']))
		{
			$this->tpl->assign("factorygoodsku", 1);
		}
        $categorylist = $this->db->get_where('db_goods_category', 'sort_id=0')->result_array();
        $attribute = $this->db->get('db_goods_type')->result_array();
        $userlist = $this->db->get_where('d_user', 'classid in (2,3,4,5,6,8,14,20) and type=1')->result_array();
        $this->tpl->assign("userlist", $userlist);
        $this->tpl->assign("attribute", $attribute);
        $this->tpl->assign("salestatus", $this->status);
        $this->tpl->assign("categorylist", $categorylist);//分类
        $this->tpl->assign("goods", $goods);//父商品信息
        $this->tpl->assign("factory", $this->m->getfactory());
        $this->tpl->display("product/EditParentProduct.tpl");
	}

    /***********
     ** 保存商品信息
     *************/
    public function saveproduct()
    {
        //先查询是否有母商品
        $sku = $this->input->post('sku');
        if ($sku == "") {
            $this->fun->phpalert(2, "SKU必须填写！", 'sku');
            die;
        }
        $this->db->trans_begin();
        $parentID = $this->m->saveparent();
        //再保存子商品信息
        $goods_id = $this->m->savegoods($parentID);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }

        //print_r($rsdb);
        header("location:/product/productlist");
    }

    /*********保存子商品信息*******/
    public function saveParentProduct()
    {
		$saveparent = $this->input->post('saveparent');
		 $parentID = $this->input->post('parentID');
		if($saveparent==1)
		{
			 $parentID = $this->m->editparent($parentID);
		}else{
	       
		    $goods_id = $this->m->savegoods($parentID);
		}
        header("location:/product/productlist?parentid={$parentID}");
    }

    /********保存单个商品信息*********/
    public function saveeditproduct()
    {
		
        $goods_id = $this->input->post('goods_id');
        $parentID = $this->input->post('parentID');
		
		//保存当前商品时如果改变状态，需要提醒
		 $goods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $goods_id . "'");    //商品信息

		 if($goods['g_sale_status'] !=$this->input->post('sale_status')){
			
			$this->fun->insertsysstatistical('status',$this->input->post('sale_status'),$goods_id,0,$this->status);
		 }
		
         $this->m->savegoods($parentID, $goods_id);
	
		
        header("location:/product/editProduct?goods_id={$goods_id}");
    }

	/*****删除单个商品信息*******/
	public function delproduct()
	{
		
		$URL = $_SERVER['HTTP_REFERER'];
		$URL = $URL?$URL:'/product/productlist';
		$goods_id = $this->input->get('goods_id');
		$goods_id = intval($goods_id);
		$this->m->getdelproduct($goods_id);
		 header("location:{$URL}");
	}
	/*****删除批量商品信息*******/
	public function batchdelgoods()
	{
		$goods_idstr = trim($this->input->post('goods_idstr'),',');
		$type = intval($this->input->post('t'));
		$type = $type?$type:0;
		if($goods_idstr)
		{
			$goods_id = explode(",",$goods_idstr);
			if($type==1)	//主SKu
			{
				foreach($goods_id as $key=>$rs)
				{
					$goods = $this->fun->getdatabaseslist('db_goods', " AND goods_parentID = '" . $rs . "'","goods_id");
					if(count($goods))
					{
						foreach($goods as $key=>$rsgoods)
						{
							$this->m->getdelproduct($rsgoods['goods_id']);
						}
					}
				}
				
			}else{
				foreach($goods_id as $key=>$rs)
				{
					$this->m->getdelproduct($rs);
				}
			}


			
		}
		echo 200;
		die;
	}
	/********查看某个商品信息********/
	public function showproduct()
	{
        $goods_id = $this->input->get('goods_id', true);
		$sku = $this->input->get('sku');

		if($_COOKIE['ext_userid'])
		{

			if($_COOKIE['ext_userid_open_goods'] == 1)	//允许查看自己组和非其他组的商品
			{
				
				$externalList = $this->fun->getdatabasesdetail('d_user_external'," AND id !='".$_COOKIE['external_id']."'",'GROUP_CONCAT(external_userID) as Createid');
				$ext_userID = $externalList['Createid'];
				$where.=" AND (g_createID not in ($ext_userID))";
			}else{
				//只能查看自己组
				$ext_userID = $_COOKIE['ext_userid'];
				$where.=" AND (g_createID in ($ext_userID))";
			}
		
		}else{
			if($_COOKIE["department"] == 1 || $_COOKIE["classid"] == 10){
			}else{
				$notext_userID = $_COOKIE['notext_userid'];
				if($notext_userID){
					$where.=" AND g_createID not in ($notext_userID)";
				}
			}
		}
		if($sku)
		{
			 $goods = $this->fun->getdatabasesdetail('db_goods', " $where AND goods_sku = '" . $sku . "' ");    //商品信息
			 $goods_id = $goods["goods_id"];
		}else{
			$goods = $this->fun->getdatabasesdetail('db_goods', " $where AND goods_id = '" . $goods_id . "'");    //商品信息
		}
		

		if(!$goods_id && !$sku)
		{
			die("缺少参数!");

		}
		if(!$goods)
		{
			die("拒绝访问!");
		}
        
		//大类
		 $bigname = $this->fun->getdatabasesdetail('db_goods_category', " AND id = '" . $goods["g_bigclassid"] . "'"); 
		 $this->tpl->assign("bigname", $bigname["cate_name"]);//分类
		if($goods["g_secondclassid"]){
		 $bigname = $this->fun->getdatabasesdetail('db_goods_category', " AND id = '" . $goods["g_secondclassid"] . "'"); 
		 $this->tpl->assign("secondclassid", $bigname["cate_name"]);//分类
		}
		if($goods["g_threeclassid"]){
		 $bigname = $this->fun->getdatabasesdetail('db_goods_category', " AND id = '" . $goods["g_threeclassid"] . "'"); 
		 $this->tpl->assign("g_threeclassid", $bigname["cate_name"]);//分类
		}

        $goods_attrlist = $this->db->get_where('db_goods_attr', 'goods_id=' . $goods_id)->result_array();//商品属性
        $goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $goods_id)->result_array();    //商品图片
        $this->db->order_by("id", 'DESC');
        $this->db->limit($this->config->item('configlognum'));
        $goods_log = $this->db->get_where('db_goods_log', 'types = 1 AND goods_id=' . $goods_id)->result_array();    //商品日志

        //属性值
        if ($goods['g_goodstypeID']) {
            $attributelist = $this->db->get_where('db_attribute', 'cat_id=' . $goods['g_goodstypeID'])->result_array();
            foreach ($attributelist as $key => $rs) {
                $rbute = $this->fun->getdatabasesdetail('db_goods_attr', " AND goods_id='" . $goods_id . "' AND attr_id='" . $rs["attr_id"] . "'");
                if ($rbute["attr_value"]) {
                    $attributelist[$key]["selectvalue"] = $rbute["attr_value"];

                }
                $attributelist[$key]["selectvaluelist"] = explode("\r\n", $rs["attr_values"]);
            }
            $this->tpl->assign("attributelist", $attributelist);
        }
		//历史订单信息
		$orderhistoryList = $this->m->getorderhistoryList($goods_id);
		if($orderhistoryList)
		{
			 $this->tpl->assign("orderhistoryList", $orderhistoryList);
		}else{
			$getorderhistoryFBAList = $this->m->getorderhistoryFBAList($goods_id);
			$this->tpl->assign("getorderhistoryFBAList", $getorderhistoryFBAList);
			
		}
        /***库存信息**/
        $storage = $this->db->get_where('db_goods_stock', " goods_id = '" . $goods_id . "'")->result_array();
        $this->tpl->assign("storage", $storage);
        $this->tpl->assign("salestatus", $this->status);
        $userlist = $this->db->get_where('d_user', 'classid in (2,3,4,5,6,8) and type=1')->result_array();
        $this->tpl->assign("userlist", $userlist);
        $this->tpl->assign("goods", $goods);
        $this->tpl->assign("goods_attrlist", $goods_attrlist);
        $this->tpl->assign("goods_images", $goods_images);
        $this->tpl->assign("goods_log", $goods_log);
        $this->tpl->assign("factory", $this->m->getfactory());
		$this->tpl->assign("classid", $_COOKIE['classid']);
        $this->tpl->display("product/showProduct.tpl");
	}
    /********销售SKU列表*********/
    public function saleskulist()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = "";

        $starttime = trim($this->input->get('starttime'));
        if ($starttime) {
            $times = $starttime . " 00:00:00";
            $where .= " AND (instime >= '" . strtotime($times) . "')";
            $this->tpl->assign("starttime", $starttime);
        }
		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$where.=" AND (createuser like '".$_COOKIE["username"]."')";
		}
        $endtime = trim($this->input->get('endtime'));
        if ($endtime) {
            $times = $endtime . " 23:59:59";
            $where .= " AND (instime <= '" . strtotime($times) . "')";
            $this->tpl->assign("endtime", $endtime);
        }
        $other = $this->input->get('other');
        if ($other) {
            $where .= " AND (goods_sku = '" . $other . "' or autosku = '" . $other . "')";
            $this->tpl->assign("other", $other);
        }
        $cu = $this->input->get('cu');
        if ($cu) {
            $where .= " AND createuser = '" . $cu . "'";
        }
        $shopid = $this->input->get('shopid');
        if ($shopid) {
            $where .= " AND (shopid = '" . $shopid . "')";
            $this->tpl->assign("shopid", $shopid);
        }
        $orderby = " order by id DESC";
        $if_csv = 0;
        if ($this->input->get('if_csv')) {
            $if_csv = 1;
        }
        $list = $this->fun->getalllist('db_salesku', $where, $nowpage, $if_csv, $this->pageSize, $orderby);

        foreach ($list["list"] as $key => $rs) {
            $rsdb = $this->fun->getdatabasesdetail('d_shop', " AND id='" . $rs["shopid"] . "'");
            $list["list"][$key]["shopname"] = $rsdb["name"];
            $list["list"][$key]["datetime"] = date("Y-m-d H:i:s", $rs["instime"]);
        }

        if ($if_csv) {
            $filename = date('YmdHis') . '.csv';
            header("Content-type: text/csv");
            header("content=text/html;charset=utf8");
            header("Content-Disposition: attachment; filename=" . $filename);
            header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');
            $str = "SKU,销售SKU,店铺,创建人\r\n";
            $pattern = '/(,)+/i';
            foreach ($list["list"] as $v) {
                $str .= "" . $v["goods_sku"] . "," . $v["autosku"] . "," . $v["shopname"] . "," . $v["createuser"] . "\r\n";
            }
            echo mb_convert_encoding($str, "cp936", "UTF-8");
            exit();
        }
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', '', 'id,name', ' order by name asc'));            //查所有店铺
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("list", $list["list"]);
        $this->tpl->display("product/saleskulist.tpl");
    }
	
    //库存查询
    public function stockSearch(){
		if($_COOKIE["classid"]==14 || $_COOKIE["classid"] == 12 || $_COOKIE["classid"] ==13 || $_COOKIE["classid"] ==16)	//工厂主管
		{
			$this->tpl->display("product/stocksearch.tpl");
			 die;
		}
        $where = "";
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")$nowpage = 1;
        //商品编号
        $other = $this->input->get_post('other');
        if($other)
        {
            $where .= " AND b.goods_sku like '%".$other."%'";
            $this->tpl->assign("other",$other);
        }
        $stockbegin = $this->input->get_post('stockbegin');
        if($stockbegin)
        {
            $where .= " AND a.stock >= $stockbegin ";
            $this->tpl->assign("stockbegin",$stockbegin);
        }
        $stockend = $this->input->get_post('stockend');
        if($stockend)
        {
            $where .= " AND a.stock <= $stockend ";
            $this->tpl->assign("stockend",$stockend);
        }
        $storage_id = $this->input->get_post('shippingStatus');
        if($storage_id){
            $where.=" AND a.storage_id = ".$storage_id;
        }
        $join = " LEFT JOIN db_goods b ON a.goods_id = b.goods_id ";
        $orderby = " ORDER BY a.id DESC ";
        $list = $this->fun->getalllist('db_goods_stock a',$where,$nowpage,$if_csv=0,$this->pageSize,$orderby,$field='*',$join);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("list",$list["list"]);
        $this->tpl->assign("warehouses",$this->db->get_where("db_storage",array('isdel'=>0))->result_array());
	
        $this->tpl->display("product/stocksearch.tpl");
    }

	//商品销量
	 public function goodssale(){
        $where = "";
		$allday = $allfabday = 0;
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")$nowpage = 1;
        //商品编号
		$where.=" AND (sales1 >0 or sales2>0 or sales3>0 or fbasale1>0 or fbasale2>0 or fbasale3>0) and goods_id !=4026";
        $other = trim($this->input->get_post('other'));
		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
        if($other)
        {
            $where .= " AND (goods_sku like '%".$other."%' or goods_parent_sku like '%".$other."%')";
            $this->tpl->assign("other",$other);
        }
		$country = trim($this->input->get('country'));
		if($country)
        {
            $this->tpl->assign("country",$country);
        }
		
		$starttime = trim($this->input->get('starttime'));
		if($starttime)
        {
			
            $this->tpl->assign("starttime",$starttime);
        }
		$endtime = trim($this->input->get('endtime'));
		if($endtime)
        {
			$sts= ",".$starttime."到".$endtime;
			$stsst= ",FBA".$starttime."到".$endtime;
            $this->tpl->assign("endtime",$endtime);
        }
      
        $orderby = " ORDER BY sales3 DESC,fbasale3 desc ";
        $list = $this->fun->getalllist('db_goods',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field='goods_id,goods_sku,goods_name,sales1,sales2,sales3,fbasale1,fbasale2,fbasale3',$join);
		foreach($list["list"] as $key=>$rs)
		{
			if($starttime && $endtime)
			{
				$list["list"][$key]["allday1"] = $allday1= $this->fun->get_goods_sale($rs["goods_id"],$starttime,$endtime,$country);
				$list["list"][$key]["allfbaday1"] =$allfabday1=$this->fun->get_goods_fba_sale($rs["goods_id"],$starttime,$endtime,$country);
			}

			$allday = $allday+$allday1;
			$allfabday = $allfabday +$allfabday1;

		}

		if($this->input->get('if_csv'))
		{
			
			if($starttime && $endtime)
			{
				$headers =array("商品编号","名称","{$starttime}到{$endtime}直销","7天销量","30天销量","60天销量","{$starttime}到{$endtime}FBA销售","FBA7天销量","FBA30天销量","FBA60天销量");
			}else{
				$headers =array("商品编号","名称","7天销量","30天销量","60天销量","FBA7天销量","FBA30天销量","FBA60天销量");
			}

			foreach($list["list"] as $key=>$rs)
			{
				$listdata[$key][] = $rs["goods_sku"]; 
				$listdata[$key][] = $rs["goods_name"]; 
				if($starttime && $endtime)
				{
					$listdata[$key][] = $rs["allday1"]; 
				}
				$listdata[$key][] = $rs["sales1"];
				$listdata[$key][] = $rs["sales2"];
				$listdata[$key][] = $rs["sales3"]; 
				if($starttime && $endtime)
				{
					$listdata[$key][] = $rs["allfbaday1"]; 
				}
				$listdata[$key][] = $rs["fbasale1"]; 
				$listdata[$key][] = $rs["fbasale2"]; 
				$listdata[$key][] = $rs["fbasale3"]; 
				
			}
			$this->fun->ouputexclePro($headers,$listdata);
		}
		
	
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allday", $allday);
		$this->tpl->assign("allfabday", $allfabday);
        $this->tpl->assign("list",$list["list"]);
        $this->tpl->assign("warehouses",$this->db->get_where("db_storage",array('isdel'=>0))->result_array());
        $this->tpl->display("product/goodssale.tpl");
    }
    public function ajaxbutton()
    {
        $op = trim($_REQUEST["op"]);
        if ($op == "saveattribute") {
            $name = $this->input->post('name');
            if ($name == "") {
                $this->fun->phpalert(2, "名称必须填写！");
                die;
            }
            $postdata["cat_name"] = $this->input->post('name');
            $postdata["enabled"] = 1;
            $res = $this->db->query($this->db->insert_string('db_goods_type', $postdata));
            $this->fun->phpalert(4, "", '', "/product/attribute");
            die;
        }
	    //添加链接 新品开发
	    if($op == "doFinish"){
		    $external_id = trim($this->input->post("external_id"));
		    $linkUrl = trim($this->input->post("linkUrl"));
		    $rsdb_develop = $this->fun->getdatabasesdetail('db_product_develop', " AND id='" . $external_id . "'");
		    if($rsdb_develop['linkUrl_addtime']){
			    $this->db->update("db_product_develop",array("linkUrl"=>$linkUrl)," id = '".$external_id."'");
		    }else{
			    $this->db->update("db_product_develop",array("linkUrl"=>$linkUrl,"linkUrl_addtime"=>date('Y-m-d H:i:s'))," id = '".$external_id."'");
		    }

		    //默认推送给设置的接收者  新品开发
		    $receivers_config = trim($this->config->item('externalbuyreceivers'));
		    $arr_receiver_config = explode("|",$receivers_config);
		    $str_receiver = "";
		    foreach($arr_receiver_config as $k=>$v){
			    $str_receiver.= "'".trim($v)."'".",";
		    }
		    $str_receiver = trim($str_receiver,",");
		    $receiverlist = $this->db->select("group_concat(id) as ids")->get_where('d_user'," type=1  AND name in ($str_receiver) ")->row_array();
		    $receivers = $receiverlist['ids'];

		    //推荐商品给接收者
			    $str_receivers = "";
			    //status 6 已完成
			    $sql = "SELECT * FROM db_product_develop WHERE status =6 AND  id= {$external_id} ";
			    $rs  = $this->db->query($sql)->row_array();
			    if(count($rs)>0){
				    if($rs['receivers']){
					    $flag = 0; //若已推荐，则不用在推荐了
				    }else{
					    $str_receivers = ",".$receivers.",";
					    $flag = 1;
				    }
				    if($flag ==1){
					    $this->db->update('db_product_develop',array('receivers'=>$str_receivers,"linkUrl_addtime"=>date('Y-m-d H:i:s'))," id = {$external_id} ");
				    }
			    }

		    echo 200;exit;
	    }
	
	    //外采购供应商 删除
	    if($op == "delSupplier"){
		    $id = trim($this->input->post('id'));
		    $this->db->delete("db_goods_purchasing"," id = '".$id."'");
		    echo 200;exit;
	    }
        if ($op == "delone") {
            if ($this->input->post('st') == "delattribute") {
                $this->db->where('cat_id', $this->input->post('id'));
                $this->db->from('db_attribute');
                $res = $this->db->count_all_results();
                if ($res == 0) {
                    $this->db->delete('db_goods_type', 'cat_id=' . $this->input->post('id'));
                    $res = array("txt" => 200, "url" => '/product/attribute');
                    echo json_encode($res);
                    die;
                } else {
                    $res = array("txt" => 201, "text" => '请先删除下级属性');
                    echo json_encode($res);
                    die;
                }
            }
            if ($this->input->post('st') == "delcategory") {
                $this->db->delete('db_goods_category', 'id=' . $this->input->post('id'));
                $res = array("txt" => 200, "url" => '/product/category');
                echo json_encode($res);
                die;
            }
            if ($this->input->post('st') == "delstorage") {
                $this->db->delete('db_storage', 'id=' . $this->input->post('id'));
                $res = array("txt" => 200, "url" => '/product/storage');
                echo json_encode($res);
                die;
            }
            if ($this->input->post('st') == "delsfexpress") {

                $res = $this->db->select()->from('db_mabangorder')->where('id=' . $this->input->post('id'))->get()->result_array();

                $this->db->delete('db_mabangorder', 'id=' . $this->input->post('id'));
				if($res[0]["orderType"]==1)$this->db->delete('db_mabangsell', 'orderid=' . $res[0]["orderID"]);
                $res = array("txt" => 200, "url" => '/order/sfexpress/'.$res[0]["orderType"]);
                echo json_encode($res);
                die;
            }
            if ($this->input->post('st') == "delattr") {
                $this->db->delete('db_attribute', 'attr_id=' . $this->input->post('id'));
                $res = array("txt" => 200, "url" => '/product/attribute');
                echo json_encode($res);
                die;
            }
            if ($this->input->post('st') == "delproductdevelop") {
                $this->db->delete('db_product_develop', 'id=' . $this->input->post('id'));
				$this->db->delete('db_productdevelop_images', 'uid=' . $this->input->post('id'));
                $res = array("txt" => 200, "url" => '/product/newproduct');
                echo json_encode($res);
                die;
            }

            if ($this->input->post('st') == 'goodsImages') {
                //删除图片商品
                $res = $this->db->select()->from('db_goods_images')->where('id=' . $this->input->post('id'))->get()->result_array();
                //$this->fun->delattfile($res[0]["local_url"]); //有些SKU是同用图片的，所以不删除原图
                $this->db->delete('db_goods_images', 'id=' . $this->input->post('id'));
                $this->fun->goods_update_log($goods_id, '删除商品图片', 1);    //更新商品信息
                $res = array("txt" => 200, "url" => '/product/editProduct?goods_id=' . $res[0]["goods_id"]);
                echo json_encode($res);
                die;
            }
			 if ($this->input->post('st') == 'productdevelop') {
                //删除新品开发图片
                $res = $this->db->select()->from('db_productdevelop_images')->where('id=' . $this->input->post('id'))->get()->result_array();
                $this->fun->delattfile($res[0]["images_url"]);
				$this->fun->delattfile($res[0]["thumb_url"]);
                $this->db->delete('db_productdevelop_images', 'id=' . $this->input->post('id'));
                $res = array("txt" => 200, "url" => '/product/newproduct?id=' . $res[0]["uid"]);
                echo json_encode($res);
                die;
            }

        }
        if ($op == "edit") {
            if ($this->input->post('st') == "editcategory") {

                $res = $this->db->select()->from('db_goods_category')->where('id=' . $this->input->post('id'))->get()->result_array();
                echo json_encode($res[0]);
                die;
            }
            if ($this->input->post('st') == "editarrt") {

                $res = $this->db->select()->from('db_attribute')->where('attr_id=' . $this->input->post('id'))->get()->result_array();
                echo json_encode($res[0]);
                die;
            }
            if ($this->input->post('st') == "editstorage") {

                $res = $this->db->select()->from('db_storage')->where('id=' . $this->input->post('id'))->get()->result_array();
                echo json_encode($res[0]);
                die;
            }


        }
	    if($op=="doRecommendGoods"){
		    $str_ids = trim($this->input->post("ids"),","); //商品编号id
		    $receivers = trim($this->input->post("receiver"),","); //用户id
		    $arr_receivers = explode(",",$receivers);
		    $arr_ids = explode(",",$str_ids);
		    foreach($arr_ids as $k=>$v){
			    $str_receivers = "";
			    //status 6 已完成
			    $sql = "SELECT * FROM db_product_develop WHERE status =6 AND  id= {$v} ";
			    $rs  = $this->db->query($sql)->row_array();
			    if(count($rs)>0){
				    if($rs['receivers']){
					    $flag = 0;
					    $receiver = trim($rs['receivers'],",");
					    $arr_receiver = explode(",",$receiver); //数据库中已存在用户
					    //新推荐用户 要过滤重复用户
					    $arr_new = array();
					    foreach($arr_receivers as $key=>$value){
						    if(in_array($value,$arr_receiver)){
							    continue;
						    }else{
							    $arr_new[] = $value;
						    }
					    }
					    if(count($arr_new)>0){
						    $str_receivers = $rs['receivers'].implode(",",$arr_new).",";
						    $flag = 1;
					    }
				    }else{
					    $str_receivers = ",".$receivers.",";
					    $flag = 1;
				    }
				    if($flag ==1){

					    $this->db->update('db_product_develop',array('receivers'=>$str_receivers,"linkUrl_addtime"=>date('Y-m-d H:i:s'))," id = {$v} ");
				    }
			    }else{
				    continue;
			    }
		    }
		    echo 200;exit; //推荐成功
	    }
        if ($op == "savecategory") {
            $name = $this->input->post('name');
            if ($name == "") {
                $this->fun->phpalert(2, "名称必须填写！");
                die;
            }
			
		    $en_name = $this->input->post('en_name');
            if ($en_name == "") {
                $this->fun->phpalert(2, "英文名称必须填写！");
                die;
            }

            $postdata["cate_name"] = $name;
			$postdata["en_name"] = $en_name;
			$postdata["sku_code"] =trim($this->input->post('sku_code'));
            $sortid = $postdata["sort_id"] = $this->input->post('sort_id');
            if ($sortid == "") {
                $this->fun->phpalert(2, "分类必须选择！");
                die;
            }
            $rsdb = $this->db->get_where('db_goods_category', 'id=' . $sortid)->result_array();
            if ($rsdb[0]['id']) {
                $rank = $rsdb[0]["rank"] + 1;
                if ($rank >= 4) {
                    $this->fun->phpalert(2, "暂时允许设置三级分类");
                    die;
                }
            } else {
                $rank = 1;
            }
            $postdata["sort"] = $this->input->post('sort');
            $postdata["rank"] = $rank;
            if ($this->input->post('id')) {
                $this->db->update('db_goods_category', $postdata, 'id=' . $this->input->post('id'));
            } else {
                $res = $this->db->query($this->db->insert_string('db_goods_category', $postdata));
            }
            $this->fun->phpalert(4, "", '', "/product/category");
        }

        if ($op == "selectcategory") {
            $categorylist = $this->db->get_where('db_goods_category', 'sort_id=' . $this->input->post('sort_id'))->result_array();
            if (count($categorylist) > 0) {
                echo json_encode($categorylist);
                die;
            } else {
                echo 201;
                die;
            }
        }
        if ($op == "showsalsku") {
            $newarray = "";
            $parent_id = trim($this->input->post('parent_id'));
            $saleskunums = $this->config->item('saleskunums');    //生成几个销售SKU
            if (!$saleskunums) $saleskunums = 1;
            $ischima = $this->config->item('ischima');    //是否自带尺码

            $shoplist = $this->db->select('id,name')->from('d_shop')->where('openflag=1')->get()->result_array();
            $shopselect = "<select name=\"saleskuarr[]\" id='saleskuarr' class=\"select2_group\" style=\"width:150px;\">";
            $shopselect .= "<option value=\"\" >请选择</option>";
            foreach ($shoplist as $r) {
                $shopselect .= "<option value=" . $r["id"] . " >" . $r["name"] . "</option>";
            }
            $shopselect .= "  </select>";
            $goodslist = $this->db->select('goods_sku,goods_id')->from('db_goods')->where('goods_parentID=' . $parent_id)->get()->result_array();
			
            if (count($goodslist) > 0) {
				$newssku="";
				$newssku = $this->m->getsalesku();

                foreach ($goodslist as $key => $rs) {
					$newgoods_sku = "";
                    if ($ischima == 1)    //系统设置带尺码
                    {
						if( $this->fun->getfactorygoodsku($rs['goods_sku']))//如果是工厂定制的衣服，需要自动生成带尺码的
						{
							$newrs = $this->m->salefactorygoodsku($newssku,$rs['goods_sku'],$rs['goods_id']);
						}


                        if (strpos($rs["goods_sku"], "-") !== false) {
                            $newgoods_sku = substr($rs["goods_sku"], strpos($rs["goods_sku"], "-"));

							//判断最后一位是字母还是数字.如果是字母则延用到新的销售SKu
							$newlastsku = explode("-",$rs["goods_sku"]);
							$newlastsku = substr($newlastsku[0],-1);
							if (preg_match ("/^[A-Za-z]/", $newlastsku)) {
								$newgoods_sku = "-".$newlastsku.$newgoods_sku;
							}else{
								$newlastsku = '';
							}
							
							if(count($arrnewchima)>0)
							{
								if(in_array($newgoods_sku,$arrnewchima))
								{
									$newgoods_sku = $newgoods_sku.$newgoods_sku;	//如果尺码已经存在，就会出现同样的销售SKU，自动增加一个尺码
								}
								
							}
							$arrnewchima[]= $newgoods_sku;
                        }

                    }
					
                    for ($i = 1; $i <= $saleskunums; $i++) {
                        $newarray[$key][$i]["sku"] = $rs["goods_sku"];
                        $newarray[$key][$i]["goods_id"] = $rs["goods_id"];
                        $newarray[$key][$i]["salesku"] = $newssku.$newgoods_sku;    //判断是否重复生成的SKU
						
                    }
					
                }
				if(count($newrs)>0)
				{
					$goodsarray = array_merge($newarray,$newrs);
				}else{
					$goodsarray =$newarray;
				}
			
				

                if (count($goodslist) > 0) {
                    $html = '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
                    foreach ($goodsarray as $key => $rs) {
                        foreach ($rs as $s => $sa) {

                            if ($key == 0) {
                                if ($this->config->item('istongshop') == 1) {
                                    $ts = "<a href=\"javascript:void(0)\" onClick=\"onsetoneshop('saleskuarr')\">同店</a><a href=\"javascript:void(0)\"><img src=\"/fuman/images/icons/question.png\"><span id=\"tip_info\">生成的SKU给同一个店铺时，使用此功能，避免销售重复对应店铺</span></a>";
                                }
                            } else {
                                $ts = "";
                            }

							//print_r(array_count_values($arrnewchima)[$sa['salesku']]);
                            $html .= " <tr> <td>$sa[sku]<input type=\"hidden\" name=\"sku[]\" value=\"$sa[sku]\"><input type=\"hidden\" name=\"skuid[]\" value=\"$sa[goods_id]\" ><input type=\"hidden\" name=\"salesku[]\" value=\"$sa[salesku]\" ></td> <td>$sa[salesku]</td> <td>$shopselect $ts</td>";
                            $html .= "</tr>";
                        }
                    }
                }
            }
            $html .= "</table>";
            echo $html;
            die;


            //	$data = array("newgoods"=>$newarray,"selectlist"=>$shopselect);
            //// echo json_encode($data);
            //   die;

        }
        if ($op == "saveattr") {
            $postdata["attr_name"] = $this->input->post('attr_name');
            if ($postdata["attr_name"] == "") {
                $this->fun->phpalert(2, "属性名称必须填写！", 'attr_name');
                die;
            }
            $postdata["cat_id"] = $this->input->post('cat_id');
            $postdata["attr_input_type"] = $this->input->post('attr_input_type');
            $postdata["attr_values_code"] = $this->input->post('attr_values_code');
            $postdata["attr_values"] = $this->input->post('attr_values');
            if ($this->input->post('attr_id')) {
                $this->db->update('db_attribute', $postdata, 'attr_id=' . $this->input->post('attr_id'));
            } else {
                $res = $this->db->query($this->db->insert_string('db_attribute', $postdata));
            }


            $this->fun->phpalert(4, "", '', "/product/attribute");
        }
        if ($op == "showattr") {
            $this->db->order_by('sort_order', 'DESC');
            $attributelist = $this->db->get_where('db_attribute', 'cat_id=' . $this->input->post('id'))->result_array();
            if (count($attributelist) > 0) {
                echo json_encode($attributelist);
                die;
            } else {
                echo 201;
                die;
            }
        }
		
		if($op =='checkcognatelist')
		{
			$cognatelist = $this->input->post('cognatelist');
			$goods_id = $this->input->post('goods_id');
			$costr = $this->fun->iscognatelist($cognatelist,$goods_id);
			if( $costr != false)
			{
				echo $costr;
				die;
			}
		}

        if ($op == "searchdevelopsku") {
			 $sku = $this->db->get_where('db_product_develop', 'sku=' . $this->input->post('sku'))->result_array();
			if(count($sku)>0)
			{
				echo 201;
				die;
			}else{echo 200;die;}
        }
        if ($op == "searchsku") {
            $res = $this->fun->getdatabasesdetail('db_goods_parent', " AND p_parent_sku='" . trim($this->input->post('sku')) . "'");
            $red = $this->fun->getdatabasesdetail('db_goods', " AND goods_sku='" . trim($this->input->post('sku')) . "'");
            if (!$res && !$red) {
                echo 200;
                die;
            } else {
				if(!$red)
				{
					 $red = $this->fun->getdatabasesdetail('db_goods', " AND goods_parent_sku='" .$res['p_parent_sku']. "'");
				}
                echo json_encode(array("res" => $res, "red" => $red));
                die;
            }
        }

        if ($op == "savestorage") {
            $postdata["storagename"] = $this->input->post('name');
            if ($postdata["storagename"] == "") {
                $this->fun->phpalert(2, "名称必须填写！");
                die;
            }
            $postdata["paixu"] = $this->input->post('paixu');
            
            $postdata['is_show'] = $this->input->post('is_show');

            $id = $this->input->post('id');
            if ($id == 0) {
                $res = $this->db->query($this->db->insert_string('db_storage', $postdata));
            } else {
                $this->db->update('db_storage', $postdata, 'id=' . $this->input->post('id'));
            }
            $this->fun->phpalert(4, "", '', "/product/storage");
            die;
        }

        if ($op == 'upimages') {
            $msg = $this->m->savedoupload();
            if ($msg["st"] != 200) {
                $this->fun->phpalert(2, $msg["txt"]);
            } else {
                $this->fun->phpalert(4, "", '', "/product/editProduct?goods_id=" . $this->input->post('goods_id'));
            }
        }

        if ($op == 'savesalesku') {
            $sku = $this->input->post('sku');
            $skuid = $this->input->post('skuid');
            $salesku = $this->input->post('salesku');
            $saleshop = $this->input->post('saleskuarr');

            foreach ($saleshop as $key => $rs) {
                if ($rs) {
                    $data["goods_id"] = $skuid[$key];
                    $data["goods_sku"] = $sku[$key];
                    $data["autosku"] = $salesku[$key];
                    $data["shopid"] = $saleshop[$key];
                    $data["instime"] = time();
                    $data["createuser"] = $_COOKIE["username"];
                    $this->db->query($this->db->insert_string('db_salesku', $data));
                }
            }
            $this->fun->phpalert(4, "", '', "/product/saleskulist?cu={$_COOKIE[username]}");
            die;
        }
        if ($op == 'savechangstatus') {
            $statusPid = $this->input->post('statusPid');
            $statusType = $this->input->post('statusType');
            $sale_status = $this->input->post('sale_status');
			 $proudctcate = $this->input->post('proudctcate');
            $this->m->savestatus($statusPid, $statusType, $sale_status,$proudctcate);
	        header("Location:"."/product/productlist?parentid={$statusPid}");
            //$this->fun->phpalert(4, "", '', "/product/productlist?parentid={$statusPid}");
        }
        //保存新品开发信息
        if ($op == 'savenewproduct') {
            $id = $this->m->saveNewProduct();
            $this->fun->phpalert(4, "", '', "/product/newproduct?id={$id}");
        }
		//显示图片信息
        if ($op == 'showImages') {
            $result = $this->m->getProductImages($this->input->post('id'));
            echo json_encode($result);
            die;
        }
		/******保存JQ传回的Images信息************/
		if($op =='saveProductImages')
		{
			$id = $this->m->saveProductImages();
			$this->fun->phpalert(4, "", '', "/product/newproduct?id={$id}");
		}
		/******保存流程状态信息************/
		if($op =='channewproductgstauts')
		{
			$this->m->channewproductgstauts();
		}
		/******保存出样填写的信息************/
		if($op =='saveProductsample')
		{
			$id = $this->m->saveProductsample();
			$this->fun->phpalert(4, "", '', "/product/newproduct?id={$id}");
		}
		/******读取单条新品的信息************/
		if($op =='getoneproductdata')
		{
			$result = $this->fun->getdatabasesdetail('db_product_develop'," AND id='".$this->input->post('id')."'");
			$result['material'] = $this->fun->getdatabaseslist('db_product_develop_material'," AND develop_id='".$this->input->post('id')."'");
			
			 echo json_encode($result);
            die;
		}
		/*********商品侵权****************/
		if($op == 'savesetinfringflag')
		{
			if($this->input->post('infring_status') ==1){
				$result = $this->fun->getdatabasesdetail('db_goods_status'," AND type=3 AND p_parent_id='".$this->input->post('infring_type')."'");
				if(!$result){
					$post = "";
					$post["p_parent_id"] = $this->input->post('infring_type');
					$post["p_parent_sku"] = $this->input->post('infring_sku');
					$post["type"] = 3;
					$post["reason"] = $this->input->post('reason');
					$post["createUser"] = $_COOKIE['username'];
					$post["createUid"] = $_COOKIE['userid'];
					$post["addTime"] =date("Y-m-d H:i:s");
					$this->db->insert('db_goods_status',$post);
				}
				$url = $_SERVER['HTTP_REFERER']? $_SERVER['HTTP_REFERER']:'/product/productlist';
				$this->fun->phpalert(4, "", '', $url);
			}else{
				$this->db->delete('db_goods_status'," type=3 AND p_parent_id='".$this->input->post('infring_type')."'");
				echo 200;
				die;
			}
		}
		/***********打印条形码******************/
		if($op =='printcode')
		{
			$str = $this->input->post('str');
			if($str)
			{
				$goods_id = substr($str,0,-1);
				$res = $this->fun->getdatabaseslist("db_goods A left join db_goods_stock B on A.goods_id = B.goods_id"," AND A.goods_id in($goods_id) AND B.storage_id = 1","goods_sku,A.goods_id,goods_name,B.positions");
			   echo json_encode($res);
              die;
			}
		}
		if($op =='saveprintcode')
		{
			$num = $this->input->post('nums');
			$goods_name = $this->input->post('goods_name');
			$positions = $this->input->post('positions');
			$goods_sku = $this->input->post('goods_sku');
			$times = date("m/d");
			if($goods_sku)
			{
				$str="";
				foreach($goods_sku as $key=>$rs)
				{
					$st = $key+1;
					for($i=1;$i<=$num[$key];$i++)
					{
						$mum = $i."/".$num[$key];
						$str.='<div style=" width:75mm; height:20mm; margin-left:2.5mm;page-break-after:always;"><ul style="width:70mm; height:8mm; margin-left:2.5mm;"><li>';
						$str.=" <img src=\"/fuman/barcode/html/image.php?filetype=PNG&dpi=72&scale=1&rotation=0&font_family=0&font_size=8&text={$rs}&thickness=30&checksum=&code=BCGcode39\" style=\" height:7mm; width:300px;\"> </li></ul>";
						$str.=' <ul style="width:70mm; height:2mm; margin-left:2.5mm;"> <li style="text-align:center; font-size:13px; font-weight:bold; width:44mm; overflow:hidden;white-space:nowrap; text-overflow:ellipsis;">';
						$str.=$goods_sku[$key];
						$str.=' </li><li style="text-align:center; font-size:12px;width:25mm;">'.$positions[$key];
						$str.="</li></ul>";
						$str.='<ul style="width:70mm; height:2mm;"><li style=" width:34mm; float:left; font-size:12px; text-align:left;">'.$goods_name[$key];
						$str.=' '.$times.'</li><li style=" width:34mm; float:left; font-size:12px; text-align:right;">'.$mum.' </li></ul>';
						$str.='<ul style="width:70mm; height:2mm;"><li style=" width:34mm; font-size:24px; text-align:center;">MADE IN CHINA</li></ul>';
						$str.='</div>';
					}
				}
				$this->tpl->assign("str", $str);
			$this->tpl->display("product/printcode.tpl",0,0,1);
			}
		
		}
		/***********打印条形码结束******************/
        if ($op == 'saveMergeProduct') //合并SKU
        {
            /*
             Array([MergeProductID] => 5605,5606,5607,5608,5609,    [ParentSku] => 11006901)
            */
            $parentSku = trim($this->input->post('ParentSku'));
            $MergeProductID = $this->input->post('MergeProductID');
            if ($parentSku) {
                $rsdb = $this->fun->getdatabasesdetail('db_goods_parent', " AND p_parent_sku = '" . $parentSku . "'", 'p_parent_id,p_parent_sku');
            }
            if ($MergeProductID && $rsdb) {
                $MergeProductID = explode(",", $MergeProductID);
				$MergeProductID = array_unique(array_filter($MergeProductID));
				
                foreach ($MergeProductID as $key => $rs) {
                    if ($rs) {
                        $resgoods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $rs . "'", 'goods_parentID');
                        $oldgoods_parentID = $resgoods["goods_parentID"];    //原来的parentID


                        $postdata = "";
                        $postdata["goods_parentID"] = $rsdb["p_parent_id"];
                        $postdata["goods_parent_sku"] = $rsdb["p_parent_sku"];
                        $this->db->update('db_goods', $postdata, 'goods_id=' . $rs);
						/*****如果有图片，需要更新图片*****/
						$resgoodsImages = $this->fun->getdatabasesdetail('db_goods', " AND goods_sku = '" . $parentSku . "'", 'goods_id');
						if($resgoodsImages["goods_id"] !=$rs && $resgoodsImages["goods_id"])
						{
							$goodsImages = $this->db->get_where('db_goods_images',"goods_id='".$resgoodsImages["goods_id"]."'")->result_array();
							if($goodsImages)
							{
								foreach($goodsImages as $k=>$r)
								{
									$Imgdata = "";
									$Imgdata["goods_id"] = $rs;
									$Imgdata["images_type"] = 1;
									$Imgdata["images_url"] = $r["images_url"];
									$Imgdata["local_url"] = $r["local_url"];
									$Imgdata["thumb_url"] = $r["thumb_url"];
									$Imgdata["filename"] = $r["filename"];
									$Imgdata["filesize"] = $r["filesize"];
									$Imgdata["createUser"] = $r["createUser"];
									$Imgdata["instime"] = $r["instime"];
									$this->db->insert("db_goods_images",$Imgdata);
								}
							}
						}

                        $resgoods = $this->fun->getdatabasesdetail('db_goods', " AND goods_parentID = '" . $oldgoods_parentID . "'", 'goods_parentID');
                        if (!$resgoods)    //Delete Parent sku
                        {
                            $this->db->delete('db_goods_parent', 'p_parent_id=' . $oldgoods_parentID);
                        }


                    }

                }
            }
            $this->fun->phpalert(4, "", '', "/product/productlist?other={$parentSku}");
        }
		
		/*********合并子SKU信息**********/
		 if ($op == 'saveMergecognatelistProudct') //合并SKU
        {
			/*******
				合并子SKU
				1、产生订单的SKU如果有配货中状态的订单不允许合并
				2、其他
			********/
            $parentSku = trim($this->input->post('ParentSku'));
            $MergeSUBProductID = $this->input->post('MergeSUBProductID');
		
            if ($MergeSUBProductID && $parentSku) {
                $MergeProductID = explode(",", $MergeSUBProductID);
				$MergeProductID = array_unique(array_filter($MergeProductID));
				
				 foreach ($MergeProductID as $key => $rs) {
					 if ($rs) {
					    $rsdb = $this->fun->getdatabasesdetail('db_goods', " AND goods_sku = '" . $parentSku . "'", 'cognatelist,goods_id,goods_sku,g_costprice');
						if(!$rsdb)
						{
							die("填写的商品编号不存在！");	
						}
						
                        $resgoods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $rs . "'", 'goods_sku,goods_id');
						//判断是否有配货中状态的订单，如果有则不允许合并
						$isorder = $this->fun->getdatabasesdetail('db_order_sell A left join db_order_list B on A.order_id=B.order_id'," AND goods_id={$resgoods[goods_id]} AND B.order_status=3");
						if($isorder)
						{
							die("商品存在配货中的订单！不允许合并！");
						}
						$postdata="";
						
						if(strpos($rsdb['cognatelist'],",".$resgoods["goods_sku"].",") === false){     //使用绝对等于
							if($rsdb['cognatelist'])
							{
								$postdata['cognatelist']  = $rsdb['cognatelist'].$resgoods["goods_sku"].",";
							}else{
								$postdata['cognatelist']  = ",".trim($resgoods["goods_sku"]).",";
							}

						}
						
						
						if($postdata)
						{
							$this->db->update("db_goods",$postdata,"goods_id = '".$rsdb['goods_id']."'");
					
							//将原SKU订单信息修改
							$this->db->update('db_order_sell',array("goods_id"=>$rsdb['goods_id'],"goods_sn"=>$rsdb['goods_sku'])," goods_id='".$resgoods['goods_id']."' ");
							$rval ="合并子SKU 原{$resgoods[goods_sku]},合并到{$rsdb[goods_sku]}";
							$this->fun->goods_update_log($rsdb["goods_id"],$rval,1);	//更新商品信息
							//将原SKU删除
							$this->m->getdelproduct($resgoods['goods_id']);
						}
					 }
				 }
              
            }
            $this->fun->phpalert(4, "", '', "/product/productlist?other={$parentSku}");
        }

		//自动获取SKU编号
		if($op =='getautoskunumber')
		{
			$bigclassID = $this->input->post('bigclassID');
			$secondclassID = $this->input->post('secondclassID');
			$sku = $this->fun->autoskunumber($bigclassID,$secondclassID);
			echo json_encode($sku);
			die;
		}

		//获取物料信息
		if($op =='getmaterialcode')
		{
			$materialcode = trim($this->input->post('materialcode'));
			$materialnum = $this->input->post('materialnum');
			$rsdb = $this->fun->getdatabasesdetail('db_factory_material'," AND code ='".$materialcode."'");
			if($rsdb)
			{
				if($materialnum)
				{
					$rsdb["materialprice"] = round($rsdb['price'] * $materialnum,2);
				}
				echo json_encode($rsdb);
				die;
			}else{
				echo 201;
				die;
			}
		}

		//批量修改采购人员
		if($op =='dochangbuyman')
		{
			$BuychangparentSKU = trim($this->input->post('BuychangparentSKU'));
			$Buychangbuyman = trim($this->input->post('Buychangbuyman'));
			$BuychangparentSKUID = trim($this->input->post('BuychangparentSKUID'),",");

			if($BuychangparentSKU)
			{
				$expgoodsno = explode("\r\n",$BuychangparentSKU);
				$url = implode(",",$expgoodsno);
				foreach($expgoodsno as $key=>$rs)
				{
					$sku = trim($rs);
					if($Buychangbuyman && $sku){
						$this->db->update("db_goods",array("g_buyer"=>$Buychangbuyman),"goods_parent_sku='".$sku."'");
					}
				}
			}

			if($BuychangparentSKUID)
			{
				$rsdb = $this->fun->getdatabasesdetail('db_goods'," AND goods_id in($BuychangparentSKUID)","GROUP_CONCAT(goods_parent_sku) as sku");
				$url = $rsdb['sku'];
				$expgoodsno = explode(",",$BuychangparentSKUID);
				foreach($expgoodsno as $key=>$rs)
				{
					$skuid = trim($rs);
					if($Buychangbuyman && $skuid){
						$this->db->update("db_goods",array("g_buyer"=>$Buychangbuyman),"goods_id='".$skuid."'");
					}
				}
			}
			 header("location:/product/productlist?other={$url}");
		}

		//提交维护申请
		if($op =='saveMaintenanceist')
		{
	
			$MaintenanceistProductID = $this->input->post('MaintenanceistProductID');
			if(!$MaintenanceistProductID)
			{
				 $this->fun->phpalert(2, "必须选择商品", '');
				 die;
			}
			$Maintenanceist = $this->input->post('Maintenanceist');
			if(!$Maintenanceist)
			{
				$this->fun->phpalert(2, "请选择建议类型和理由", '');
				 die;
			}
			$Maintenanceistbmemo = $this->input->post('Maintenanceistbmemo');
			if(!$Maintenanceistbmemo)
			{
				$this->fun->phpalert(2, "请填写理由", '');
				 die;
			}
			$memo = "【".$_COOKIE['username'].$Maintenanceist."】".$Maintenanceistbmemo;
			$protector = trim($this->input->post('protector'));
			$res = $this->m->saveMaintenanceist($MaintenanceistProductID,$memo,$protector);
			if($res==201)
			{
				$this->fun->phpalert(2, "提交维护成功！等待维护人员反馈", '');
			}else{
				$this->fun->phpalert(2, "以下商品不能申请维护：".$res, '');
			}
		}

		//从马帮导入商品信息，按成本
		if($op =='doImportProduct')
		{
			require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel/IOFactory.php';
			$res = $this->fun->newupfile('file_excel','product');
			$upfile =BASEPATH.'../uploads/'.$res['pic'];
			if(!file_exists($upfile))
			{
				echo "没找到文件->". $upfile;
				die;
			}
			$Importtyps = $this->input->post('Importtyps');
			if($Importtyps==2)
			{
				//更新新的SKU信息
				$this->m->ImportNewProduct($upfile,2);

			}else{
				//更新开发期的产品信息
				$this->m->ImportNewProduct($upfile,1);
			}
			echo "OK";

		}
		/***********从马帮导入新的SKU信息，按仓位导******************/
		if($op == 'inputexcel')
		{
			require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel/IOFactory.php';
			$upfile = BASEPATH."../fuman/cangwei.xls";
			if(!file_exists($upfile))
			{
				echo "没找到文件->". $upfile;
				die;
			}
			if($resExcel = PHPExcel_IOFactory::load($upfile)){
				$allRow = $resExcel->getActiveSheet()->getHighestRow();
				$s = 0;
				for($i=1;$i<=$allRow;++$i){
					$A=trim($resExcel->getActiveSheet()->getCell('A'.$i)->getValue());	//sku
					$B=trim($resExcel->getActiveSheet()->getCell('B'.$i)->getValue());	//仓位
					
					$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".$A."'");
					if(!$rsdb)
					{
						$goodsno =  $A;
						//判断是否包含-
						$expgoodsno = explode("-",trim($goodsno));
						if(count($expgoodsno)>=2){
							$parent_goods = $expgoodsno[0];
						}else{
							$parent_goods = trim($goodsno);
						}
						
						$this->load->library('Formmabangsku');
						$goods_id = $this->formmabangsku->getsaveParent($parent_goods,$A,$B);//传入一个SKU如果父SKU存在，则返回ID，不存在则创建

						
						echo $A;
						echo "->";
						echo $goods_id;
						echo "<br>";
					}
					
					
			

				}
			}
		}

    }
}
